package qx.hyj.petrescue.controller;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import qx.hyj.petrescue.VO.Result;
import qx.hyj.petrescue.entity.BaseEntity;
import qx.hyj.petrescue.exception.DescribeException;
import qx.hyj.petrescue.param.ConditionParam;
import qx.hyj.petrescue.param.PageModel;
import qx.hyj.petrescue.param.PageParam;
import qx.hyj.petrescue.service.IBaseService;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public abstract class BaseControllerImpl<T extends BaseEntity<K>, K extends Serializable> implements IBaseController<T, K> {

    private static final Logger logger = LoggerFactory.getLogger(BaseControllerImpl.class);

    @Resource
    private IBaseService<T, K> service;

    //@Autowired
    // private BaseMapper<T> baseMapper;

    @Override
    public Class<? extends Type> getEntityClass() {
        Type genericSuperclass = this.getClass().getGenericSuperclass();
        if (genericSuperclass instanceof ParameterizedType) {
            Type[] actualTypeArguments = ((ParameterizedType) genericSuperclass).getActualTypeArguments();
            if (actualTypeArguments.length > 0) {
                if (actualTypeArguments[0] instanceof Class) {
                    return (Class<? extends Type>) actualTypeArguments[0];
                }
                return actualTypeArguments[0].getClass();
            }
        }
        return null;
    }

    @Override
    @Operation(summary = "添加接口", description = "添加接口")
    @PostMapping("/add")
    public Result<T> add(@RequestBody T data, HttpServletRequest request) {
        K k = data.genPrimary();
        data.setPrimary(k);
        boolean save = service.save(data);
        // LogUtil.op(request, "添加" + getEntityName(), "添加" + getEntityName());
        if (save) {
            return Result.success(data);
        }
        return Result.failure(-1, "添加失败");
    }

    @Override
    @Operation(summary = "更新接口", description = "更新接口")
    @PutMapping("/update")
    public Result<T> update(@RequestBody T data, HttpServletRequest request) {
        K primary = data.getPrimary();
        if (primary == null) {
            return Result.failure(-1, "未传入主键");
        }
        // LogUtil.op(request, "更新" + getEntityName(), "更新" + getEntityName());
        boolean update = service.updateById(data);
        if (update) {
            return Result.success(data);
        }
        return Result.failure(-1, "更新失败");
    }

    @Override
    @Operation(summary = "删除接口", description = "删除接口")
    @DeleteMapping("/delete")
    public Result<K> delete(
            @Parameter(name = "id", description = "主键编号id")
            @RequestParam(name = "id") K id, HttpServletRequest request) {
        if (id == null) {
            return Result.failure(-1, "未传入主键");
        }
        // LogUtil.op(request, "删除" + getEntityName(), "删除" + getEntityName());
        boolean remove = service.removeById(id);
        if (remove) {
            return Result.success();
        }
        return Result.failure(-1, "删除失败");
    }

    @Override
    @Operation(summary = "详情接口", description = "详情接口")
    @GetMapping("/get")
    @Parameter(name = "id", description = "主键编号id")
    public Result<T> get(
            @RequestParam(name = "id") K id, HttpServletRequest request) {
        T byId = service.getById(id);
        // LogUtil.op(request, "查询" + getEntityName() + "详情", "查询" + getEntityName() + "详情");
        return Result.success(byId);
    }

    @Override
    @Operation(summary = "批量删除接口", description = "批量删除接口")
    @Parameter(name = "ids", description = "id列表")
    @DeleteMapping("/deleteBatch")
    public Result<List<K>> deleteBatch(
            @RequestParam(required = false) String ids, HttpServletRequest request) {
        List<String> idList = null;
        if (!StringUtils.isEmpty(ids)) {
            String[] split = ids.split(",");
            idList = Arrays.asList(split);
        }
        if (idList == null) {
            return Result.failure(-1, "未传入主键");
        }
        // LogUtil.op(request, "批量删除" + getEntityName() + "", "批量删除" + getEntityName() + "");
        boolean remove = service.removeByIds(idList);
        if (remove) {
            return Result.success();
        }
        return Result.failure(-1, "删除失败");
    }

    @Operation(summary = "分页查询接口", description = "分页查询接口")
    @PostMapping("/page")
    public Result<PageModel<List<T>>> page(
            @RequestBody @Parameter(description = "分页信息") PageParam<T> pageParam,
            HttpServletRequest request) {
        Integer pageNum = pageParam.getPageNum();
        Integer pageSize = pageParam.getPageSize();
        Page<T> tPage = new Page<>(pageNum, pageSize);
        T condition = pageParam.getCondition();
        QueryWrapper<T> queryWrapper = new QueryWrapper<>(condition);
        T filter = pageParam.getFilter();
        if (filter != null) {
            Map<String, Object> beanToMap = BeanUtil.beanToMap(filter, false, true);
            for (Map.Entry<String, Object> entry : beanToMap.entrySet()) {
                String key = entry.getKey();
                Object value = entry.getValue();
                queryWrapper.like(key, value);
            }
        }
        Class<?> aClass = getEntityClass();
        String asc = pageParam.getAsc();
        String desc = pageParam.getDesc();
        if (aClass != null) {
            Field[] declaredFields = aClass.getDeclaredFields();
            for (Field declaredField : declaredFields) {
                String name = declaredField.getName();
                if (StringUtils.isBlank(name)) {
                    continue;
                }
                if (name.equals(asc)) {
                    queryWrapper.orderByAsc(asc);
                    continue;
                }
                if (name.equals(desc)) {
                    queryWrapper.orderByDesc(desc);
                }
            }
        }
        boolean xgsjOrderDesc = false;
        if (aClass != null) {
            Field[] declaredFields = aClass.getDeclaredFields();
            for (Field declaredField : declaredFields) {
                String name = declaredField.getName();
                if ("xgsj".equals(name)) {
                    xgsjOrderDesc = true;
                    break;
                }
            }
        }
        queryWrapper.orderByDesc(xgsjOrderDesc, "xgsj");
        Page<T> page1 = null;
        try {
            page1 = service.page(tPage, queryWrapper);
        } catch (Exception e) {
            logger.info(e.getMessage());

        }
        if (null == page1) {
            throw new DescribeException("查询失败");
        }

        List<T> records = page1.getRecords();
        PageModel<List<T>> listPageModel = new PageModel<>(page1.getTotal(), records);

        return Result.success(listPageModel);
    }

    @Operation(summary = "查询接口", description = "查询接口")
    @PostMapping("/list")
    public Result<List<T>> list(
            @RequestBody @Parameter(description = "条件参数") ConditionParam<T> conditionParam,
            HttpServletRequest request) {
        return Result.success(service.list(conditionParam, request));
    }

}
